package cn.nbs.cart.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import cn.com.hkr.commons.CommonUtils;
import cn.com.hkr.jdbc.TxQueryRunner;
import cn.nbs.book.entity.Book;
import cn.nbs.cart.entity.CartItem;
import cn.nbs.user.entity.User;

public class CartItemDao {
	private TxQueryRunner qr = new TxQueryRunner();
	
	/**
	 * 通过bid，uid查询购物车条目
	 * @param bid
	 * @param uid
	 * @return
	 */
	public CartItem findByBidAndUid(String bid, String uid) {
		String sql = "select * from t_cartitem where bid = ? and uid  = ?";
		try {
			return qr.query(sql, new BeanHandler<CartItem>(CartItem.class),bid,uid);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 添加购物车条目
	 * @param item
	 */
	public void addCartItem(CartItem item) {
		String sql = "insert into t_cartitem value(?,?,?,?,null)";
		try {
			qr.update(sql,item.getCartItemId(),item.getQuantity(),item.getBook().getBid(),item.getUser().getUid());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
	}

	/**
	 * 更新购物车数量
	 * @param cartItemId
	 * @param i
	 */
	public void updateQuantity(String cartItemId, int i) {
		String sql = "update t_cartitem set  quantity  =  ? where cartItemId = ?";
		try {
			qr.update(sql,i,cartItemId);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 通过uid查询购物车条目
	 * @param uid
	 * @return
	 */
	public List<CartItem> findByUid(String uid) {
		String sql = "select * from t_cartitem s,t_book b,t_user u where s.bid = b.bid  and u.uid = s.uid and s.uid  = ?";
		try {
			
			//通过查询购物车条目，先封装书对象，然后将书对象封装到购物车条目里
			List<Map<String,Object>> mapList = qr.query(sql, new MapListHandler(),uid);
			
			//将书的信息封装到书的对象里，将用户信息封装到用户对象中
			List<CartItem> list = new ArrayList<CartItem>();
			
			for (Map<String,Object> cartItemmap : mapList) {
				CartItem item  = findListByBid(cartItemmap);
				list.add(item);
			}
			return list;
		
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 通过购物车查询对应的书籍
	 * @param list
	 */
	private CartItem findListByBid(Map list) {
		
		CartItem cartitem = CommonUtils.toBean(list, CartItem.class);
		Book book = CommonUtils.toBean(list, Book.class);
		User user = CommonUtils.toBean(list, User.class);
		
		cartitem.setBook(book);
		cartitem.setUser(user);
		return cartitem;
	}

}
